package com.example.power_service.jwt;

import com.example.power_service.otherservice.Otherservice;
import com.google.common.collect.Maps;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.Map;
@Component
public class JWTUtils
{
    //token 有效期
    @Value("${token.indate}")
    private  long indate;


    @Autowired
     Otherservice otherservice;

    //秘钥
    private static final String PRIVTE_KEY="GZJYYDS";


    //创建token
    public   String createtoken(int userid){

        //得到线程安全的Map对象
        Map claims = Maps.newConcurrentMap();

        //将用户id作为数据保存
        claims.put("userid", userid);

        JwtBuilder jwtBuilder= Jwts.builder();
        Date date=new Date();
        //设置数据
        jwtBuilder.setClaims(claims);
        //设置签发时间
        jwtBuilder.setIssuedAt(date);
        //设置过期时间
        date.setTime(date.getTime()+indate);
        jwtBuilder.setExpiration(date);
        //设置标题
        jwtBuilder.setSubject("ggtoken");
        //设置加密方式以及秘钥
        jwtBuilder.signWith(SignatureAlgorithm.HS256,PRIVTE_KEY);

        return jwtBuilder.compact();
    }


    public  Map checktoken(String token){
        //返回验证结果
        Map res=Maps.newConcurrentMap();
       //根据秘钥获取token中的挂载数据对象
        Claims claims= null;
        try {
            Jws<Claims> claimsJws=Jwts.parser().setSigningKey(PRIVTE_KEY).parseClaimsJws(token);
            claims = claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            //验证token是否在有效期
            res.put("path", false);
            res.put("data","token Invalid! Please log in again");
            return res;
        }


        //从token中获取userid
        int userid=(int)claims.get("userid");
        //验证用户信息是否属实

        if (otherservice.checklogin(userid)==null){
            res.put("path", false);
            res.put("data","false token！");
            return res;
        }

        //如果token有效期将近则重新颁发token
        if (new Date().getTime()-claims.getExpiration().getTime()<indate/2){


            res.put("path", true);
            res.put("data",userid);

            return res;
        }

        //验证成功
        res.put("path", true);
        res.put("data","token Validation succeeded !");

        return res;
    }
}
